import { _decorator, Component, instantiate, Node, Prefab, Vec3, Collider2D,Animation, IPhysics2DContact, Contact2DType, find } from 'cc';
import { GameManager, GameState } from '../GameManager';
const { ccclass, property } = _decorator;

@ccclass('Ships_Human')
export class Ships_Human extends Component {
    // @property(Prefab)
    // bullet_1: Prefab | null = null; // 使用单个子弹Prefab
    @property(Prefab)
    bullet_1:Prefab=null;

    @property(Node)
    gunL:Node=null;
    @property(Node)
    gunR:Node=null;

    private lastBulletTime: number = 0; // 上一次生成子弹的时间
    private attackCount: number = 0; // 当前是第几次发射子弹
    @property
    private maxBullets: number = 4; // 最大子弹数量
    private bulletSpacing: number = 11.5; // 子弹之间的间距，单位为游戏单位
    
    @property(Animation)
    anim:Animation = null;

    start() {
        // 游戏开始时不发射子弹，等待 update 方法控制发射
    }

    update(deltaTime: number) {
        const currentTime = Date.now();
        if (currentTime - this.lastBulletTime >= 700) { // 每隔1000毫秒（1秒）调用
            this.lastBulletTime = currentTime;

            if(GameManager.getInstance().gameState==GameState.START){
                this.generateBullets();
            }
            this.attackCount = (this.attackCount + 1) % (this.maxBullets + 1); // 更新攻击次数
        }
    }
    
    private generateBullets() {
        if (this.bullet_1) {
            const PlayerBullets = find("Canvas/BG/Bullets"); // 假设子弹是在玩家节点下生成
            const newPosL = this.gunL.getWorldPosition();
            const newPosR = this.gunR.getWorldPosition();

            for (let i = 0; i < this.attackCount; i++) {
                const newBullet = instantiate(this.bullet_1);
                PlayerBullets.addChild(newBullet);
                this.anim.play("ships_human_Shoot");
                
                // 根据子弹数量计算x坐标偏移量
                let offsetX = (i - (this.attackCount - 1) / 2) * this.bulletSpacing;
                const bulletPos = new Vec3(newPosL.x + offsetX, newPosL.y, newPosL.z);

                // 设置子弹的位置
                newBullet.setWorldPosition(bulletPos);

            }
            for (let i = 0; i < this.attackCount; i++) {
                const newBullet = instantiate(this.bullet_1);
                PlayerBullets.addChild(newBullet);
                
                // 根据子弹数量计算x坐标偏移量
                let offsetX = (i - (this.attackCount - 1) / 2) * this.bulletSpacing;
                const bulletPos = new Vec3(newPosR.x + offsetX, newPosR.y, newPosR.z);

                // 设置子弹的位置
                newBullet.setWorldPosition(bulletPos);

            }
        }
    }

}